package com.ifast.face.service.run;

import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.Frame;
import org.bytedeco.javacv.FrameGrabber;

import cn.hutool.core.util.NumberUtil;
/**
 * 
 * @author shíQíang㊚
 * 2019年8月19日10:25:00
 *
 */
public class FrameGrabberAdapter{
	
	private String url;
	private int stimeOut;
	private int width;
	private int height;
	private int frameRate;
	private FrameGrabber grabber;
	 
	public FrameGrabberAdapter(String url,int stimeOut,int width,int height,int frameRate){
		this.url = url;
		this.stimeOut = stimeOut;
		this.width = width;
		this.height = height;
		this.frameRate = frameRate;
	}
	
	public Frame grab(){
		try {
			return grabber.grab();
		} catch (Exception e) {
			//需要根据 一次类型进行重启restart();
			e.printStackTrace();
			return null;
		}
	}
	
	public void start(){ 
	 	try {
	 		builder(); 
	 		grabber.start();//开启抓取器 
		} catch (Exception e){
			e.printStackTrace(); 
		} 
	} 
	
	private void builder() throws Exception{ 
		if(NumberUtil.isNumber(url)){
			grabber = FrameGrabber.createDefault(url);
		}else{
			grabber = FFmpegFrameGrabber.createDefault(url);
		}
		/*
         * "timeout" - IS IGNORED when a network cable have been unplugged
         * before a connection and sometimes when connection is lost.
         *
         * "rw_timeout" - IS IGNORED when a network cable have been
         * unplugged before a connection but the option takes effect after a
         * connection was established. 
         * "stimeout" - works fine.
         */
		grabber.setOption(TimeoutOption.STIMEOUT.key(),String.valueOf(stimeOut * 1000000));
		//grabber.setOption("rtsp_transport", "tcp");
		// -map指定哪些流做为输入， 0:0 表示第0个输入文件的第0个流
//		grabber.setOption("map","0:0"); 
		grabber.setFrameRate(frameRate); 
		grabber.setImageWidth(width);
	 	grabber.setImageHeight(height);
	 	
	}
	
	/**
     * There is no universal option for streaming timeout. Each of protocols has
     * its own list of options.
     */
    private enum TimeoutOption {
        /*
         * Depends on protocol (FTP, HTTP, RTMP, SMB, SSH, TCP, UDP, or UNIX).
         * http://ffmpeg.org/ffmpeg-all.html
         */
        TIMEOUT,
        /*
         * Protocols
         * Maximum time to wait for (network) read/write operations to complete,
         * in microseconds.
         * http://ffmpeg.org/ffmpeg-all.html#Protocols
         */
        RW_TIMEOUT,
        /*
         * Protocols -> RTSP
         * Set socket TCP I/O timeout in microseconds.
         * http://ffmpeg.org/ffmpeg-all.html#rtsp
         */
        STIMEOUT; 
   
		public String key(){
            return toString().toLowerCase();
        }

    }
	 
	public void close() throws org.bytedeco.javacv.FrameGrabber.Exception{
		grabber.stop(); 
		grabber.release();
	} 
}
